#include "TextUtils.h"
#include <locale>

namespace ECS
{
	namespace details
	{
		void reverse(char* s)
		{
			int i, j;
			char c;

			for (i = 0, j = strlen(s)-1; i<j; i++, j--) 
			{
				c = s[i];
				s[i] = s[j];
				s[j] = c;
			}
		}

		char* itoa(int n, char* s, int base=10)
		{
			static const char* digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
			int i, sign;

			if ((sign = n) < 0)  
				n = -n;          
			i = 0;
			do 
			{       
				s[i++] = digits[n % base];   
			} 
			while ((n /= base) > 0);     
			if (sign < 0)
				s[i++] = '-';
			s[i] = '\0';
			reverse(s);

			return s;
		}

		char* utoa(unsigned int n, char* s, unsigned int base=10)
		{
			static const char* digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
			unsigned int i;

			i = 0;
			do 
			{       
				s[i++] = digits[n % base];   
			} 
			while ((n /= base) > 0);     
			s[i] = '\0';
			reverse(s);

			return s;
		}
	}

	int TextUtils::toInt32(const char* crValue)
	{
		return atoi(crValue);
	}
	int TextUtils::toInt32(const std::string & crValue)
	{
		return atoi(crValue.c_str());
	}

	float TextUtils::toFloat( const char* crValue )
	{
		return (float)atof(crValue);
	}

	float TextUtils::toFloat(const std::string & crValue)
	{
		return (float)atof(crValue.c_str());
	}

	bool TextUtils::toBool( const char* crValue )
	{
		return toBool(std::string(crValue));
	}

	bool TextUtils::toBool(const std::string& crValue)
	{
		if (crValue == "0")
			return false;
		if (crValue == "1")
			return true;
		return toLowerCase(crValue) == "true";
	}

	std::string TextUtils::toLowerCase( const std::string& value )
	{
		std::string result = value;

		for (auto it = result.begin(); it != result.end(); ++it)
		{
			*it = std::tolower<char>(*it, std::locale(""));
		}
		return result;
	}
}
